// 源插件
import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
import { NumberDivide, DateDiff, FormatnumberZero, Mover, DateStamp } from '@/function.js';

// 视图插件
import {
  BackTop,
  Empty,
  Spin,
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
  Upload,
} from 'antd';

// 外部组件
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Loading from '@/components/Loading/Loading';
import TimelineChartSeven from '@/components/Charts/TimelineChartSeven';

// css OR less预编译器
import styles from './All.less';

// 图片

const Option = { Select };

/**
 *  Describe:数据连接
 *  Created by xjc on 2019/5/15
 */

@connect(({ runpoints, loading }) => ({
  runpoints,
  loading: loading.models.runpointsRule,
}))
@Form.create()
class RunPoints extends PureComponent {
  componentWillMount() {}

  /**
   *  Describe:当前状态
   *  Created by xjc on 2019/5/15
   */

  state = {
    listLoading: false, // 加载状态
    selectedRows: [], // 选择行
    formValues: {
      num: 10,
      page: 1,
    }, // 表格参数
    /* pageValues:{current: 1, pageSize: 10, total: 0}, */
    StocksDetailVisible: false, // modal开关
    OptionVisible: false, // modal开关
    record: {}, // 当前行内容
    searchText: '', // 搜索内容
    columns: [], // 表头处理结果
    currentDataSource: [], // 表剩余数据
    Beta: '比较BETA值', // 表剩余数据
    modalVisible: false,
  };

  /**
   *  Describe:本地搜索
   *  Created by xjc on 2019/6/4
   */

  getColumnSearchProps = dataIndex => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
      <div style={{ padding: 8 }}>
        <Input
          ref={node => {
            this.searchInput = node;
          }}
          placeholder={`Search ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => this.handleSearch(selectedKeys, confirm)}
          style={{ width: 188, marginBottom: 8, display: 'block' }}
        />
        <Button
          type="primary"
          onClick={() => this.handleSearch(selectedKeys, confirm)}
          icon="search"
          size="small"
          style={{ width: 80, marginRight: 8 }}
        >
          搜索
        </Button>
        <Button onClick={() => this.handleReset(clearFilters)} size="small" style={{ width: 80 }}>
          重置
        </Button>
      </div>
    ),
    filterIcon: filtered => (
      <Icon type="search" style={{ color: filtered ? '#1880ff' : '#181816', fontWeight: '700' }} />
    ),
    onFilter: (value, record) => {
      if (record[dataIndex] === '股票合计') {
        return true;
      }
      return record[dataIndex] === null
        ? ''
        : record[dataIndex]
            .toString()
            .toLowerCase()
            .includes(value.toLowerCase());
    },
    onFilterDropdownVisibleChange: visible => {
      if (visible) {
        setTimeout(() => this.searchInput.select());
      }
    },
    render: text => <span>{text}</span>,
  });

  handleSearch = (selectedKeys, confirm) => {
    confirm();
    this.setState({ searchText: selectedKeys[0] });
  };

  handleReset = clearFilters => {
    clearFilters();
    this.setState({ searchText: '' });
  };

  getColumns() {
    const {
      runpoints: { stocksFilters },
    } = this.props;
    return [
      /*    {
            title: '序号',
            dataIndex: 'p',
          }, */
      {
        title: '股票代码',
        align: 'center',
        dataIndex: 'stock',
        width: 120,
        sorter: (a, b) => {
          const c = [a.stock, b.stock].sort();
          if (c[0] === a.stock) {
            return 1;
          }
          return -1;
        },
        ...this.getColumnSearchProps('stock'),
        render: (value, row, index) => {
          return <span>{row.epsCompare === 1 ? ` * ${value}` : `${value}`}</span>;
        },
      },
      {
        title: '跑赢SPY比率(1周）',
        dataIndex: 'rateOneWeek',
        align: 'center',
        width: 100,
        sorter: (a, b) => a.rateOneWeek - b.rateOneWeek,
        render: (value, row, index) => {
          return (
            <span>
              {typeof value === 'number' || typeof value === 'string'
                ? `${value}(${row.dayOneWeek})`
                : null}
            </span>
          );
        },
      },
      {
        title: '跑赢SPY比率(2周）',
        align: 'center',
        dataIndex: 'rateTwoWeek',
        width: 100,
        sorter: (a, b) => a.rateTwoWeek - b.rateTwoWeek,
        render: (value, row, index) => {
          return (
            <span>
              {typeof value === 'number' || typeof value === 'string'
                ? `${value}(${row.dayTwoWeek})`
                : null}
            </span>
          );
        },
      },
      {
        title: '跑赢SPY比率(1月）',
        align: 'center',
        dataIndex: 'rateOneMonth',
        width: 100,
        sorter: (a, b) => a.rateOneMonth - b.rateOneMonth,
      },
      {
        title: '跑赢SPY比率(3月）',
        align: 'center',
        dataIndex: 'rateThreeMonth',
        width: 100,
        sorter: (a, b) => a.rateThreeMonth - b.rateThreeMonth,
      },
      {
        title: '跑赢SPY比率(6月）',
        align: 'center',
        dataIndex: 'rateSixMonth',
        width: 100,
        sorter: (a, b) => a.rateSixMonth - b.rateSixMonth,
      },
      {
        title: '跑赢SPY比率(1年）',
        align: 'center',
        dataIndex: 'rateOneYear',
        width: 100,
        sorter: (a, b) => a.rateOneYear - b.rateOneYear,
      } /* {
        title: '跑分时间',
        dataIndex: 'uploadTime',
        width:120,
        align: 'center',
        sorter: (a, b) => DateStamp(a.uploadTime) - DateStamp(b.uploadTime),
        // render: (value, row, index) => {
        //   return <span >{typeof value === 'string'?value.split(' ')[0]:''}</span>
        // }
      }, */,
    ];
  }

  getColumnsBeta() {
    const {
      runpoints: { stocksFilters },
    } = this.props;
    return [
      /*    {
            title: '序号',
            dataIndex: 'p',
          }, */
      {
        title: '股票代码',
        align: 'center',
        dataIndex: 'stock',
        width: 120,
        sorter: (a, b) => {
          const c = [a.stock, b.stock].sort();
          if (c[0] === a.stock) {
            return 1;
          }
          return -1;
        },
        ...this.getColumnSearchProps('stock'),
        render: (value, row, index) => {
          return <span>{row.epsCompare === 1 ? ` * ${value}` : `${value}`}</span>;
        },
      },
      {
        title: '跑赢SPY比率(1周）/Beta',
        dataIndex: 'betaRateOneWeek',
        align: 'center',
        width: 100,
        sorter: (a, b) => a.betarateOneWeek - b.betarateOneWeek,
        render: (value, row, index) => {
          return (
            <span>
              {typeof value === 'number' || typeof value === 'string'
                ? `${value}(${row.dayBetaOneWeek})`
                : null}
            </span>
          );
        },
      },
      {
        title: '跑赢SPY比率(2周）/Beta',
        align: 'center',
        dataIndex: 'betaRateTwoWeek',
        width: 100,
        sorter: (a, b) => a.betarateTwoWeek - bbeta.rateTwoWeek,
        render: (value, row, index) => {
          return (
            <span>
              {typeof value === 'number' || typeof value === 'string'
                ? `${value}(${row.dayBetaTwoWeek})`
                : null}
            </span>
          );
        },
      },
      {
        title: '跑赢SPY比率(1月）/Beta',
        align: 'center',
        dataIndex: 'betaRateOneMonth',
        width: 100,
        sorter: (a, b) => a.betarateOneMonth - b.betarateOneMonth,
      },
      {
        title: '跑赢SPY比率(3月）/Beta',
        align: 'center',
        dataIndex: 'betaRateThreeMonth',
        width: 100,
        sorter: (a, b) => a.betarateThreeMonth - b.betarateThreeMonth,
      },
      {
        title: '跑赢SPY比率(6月）/Beta',
        align: 'center',
        dataIndex: 'betaRateSixMonth',
        width: 100,
        sorter: (a, b) => a.betaRateSixMonth - b.betaRateSixMonth,
      },
      {
        title: '跑赢SPY比率(1年）/Beta',
        align: 'center',
        dataIndex: 'betaRateOneYear',
        width: 100,
        sorter: (a, b) => a.betaRateOneYear - b.betaRateOneYear,
      } /* {
        title: '跑分时间',
        dataIndex: 'uploadTime',
        width:120,
        align: 'center',
        sorter: (a, b) => DateStamp(a.uploadTime) - DateStamp(b.uploadTime),
        // render: (value, row, index) => {
        //   return <span >{typeof value === 'string'?value.split(' ')[0]:''}</span>
        // }
      }, */,
    ];
  }

  handleStandardTableChange = (pagination, filtersArg, sorter, extra) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    this.setState({
      currentDataSource: extra.currentDataSource,
      total: extra.currentDataSource.length - 1,
    });
    /* 导入列表数据 */
    /*  dispatch({
        type: 'runpoints/GetUBSPosition',
        payload: {
          param:3,
          currentDataSource:extra.currentDataSource
        },
        callback: (res) => {

        }
      }); */
  };

  onSelectType(value) {
    const { dispatch } = this.props;
    dispatch({
      type: 'runpoints/GetRunPoints',
      payload: value,
      callback: res => {
        this.setState({
          currentDataSource: res.list,
        });
      },
    });
  }

  changeBeta() {
    if (this.state.Beta === '不比较BETA值') {
      this.setState({
        Beta: '比较BETA值',
      });
    } else {
      this.setState({
        Beta: '不比较BETA值',
      });
    }
  }

  doubleClick(record) {
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'runpoints/GetStockHistoryRunPoint',
      payload: {
        stock: record.stock,
        betaFlag: that.state.Beta === '比较BETA值',
      },
      callback: res => {
        that.setState({
          codes: record.stock,
          chart: res.list,
          modalVisible: true,
        });
      },
    });
  }

  cancelHandle() {
    this.setState({
      modalVisible: false,
    });
  }

  /**
   *  Describe:视图
   *  Created by xjc on 2019/5/15
   */

  render() {
    const {
      loading,
      runpoints: { stocks },
    } = this.props;
    const {
      listLoading,
      selectedRows,
      record,
      StocksDetailVisible,
      OptionVisible,
      currentDataSource,
      Beta,
    } = this.state;
    const { chart, modalVisible, codes } = this.state;
    let columns = [];
    let columnsBeta = [];
    const stocksList = [];
    if (columns.length === 0 && stocks.code === 1) {
      columns = this.getColumns();
      columnsBeta = this.getColumnsBeta();
    }
    return (
      <PageHeaderWrapper title="跑分系统">
        <Card>
          <Row>
            <Col md={10} sm={24}>
              类型：
              <Select
                placeholder="请选择"
                style={{ width: '60%', margin: 8 }}
                onSelect={this.onSelectType.bind(this)}
              >
                <Option value={1}>新二号持仓股票</Option>
                <Option value={2}>新二号持仓ETF</Option>
                <Option value={3}>郭老师多头股票池</Option>
                <Option value={4}>多头ETF池</Option>
                <Option value={5}>所有持仓股票跑分</Option>
              </Select>
              <Button onClick={this.changeBeta.bind(this)} style={{ margin: 8 }} type="primary">
                {Beta === '不比较BETA值' ? '比较BETA值' : '不比较BETA值'}
              </Button>
            </Col>
          </Row>
          <br />
          {stocks.code === 0 ? (
            <Loading />
          ) : Beta === '不比较BETA值' ? (
            <div>
              <div style={{ margin: 5, fontSize: '1rem' }}>
                标星股票：eps、gaap eps两值相差>=80%}
              </div>
              <div style={{ margin: 5, fontSize: '1rem' }}>
                共计：{currentDataSource.length}&nbsp;&nbsp;&nbsp;跑分时间：
                {stocks.list.length === 0 ? null : stocks.list[0].uploadTime}
              </div>
              <StandardTable
                selectedRows={selectedRows}
                loading={listLoading}
                data={stocks}
                columns={columns}
                style={{ tableLayout: 'fixed' }}
                className={styles.TableLayout}
                scroll={{ x: window.outerWidth < 600 ? 900 : 1400, y: 618 }}
                bordered
                onChange={this.handleStandardTableChange}
                pagination={false}
                onRow={record => {
                  const res = record;
                  return {
                    onClick: event => {
                      if (this.doubleClick) {
                        this.doubleClick(res);
                      }
                    },
                  };
                }}
                // rowKey="id"
              />
            </div>
          ) : (
            <div>
              <div style={{ margin: 5, fontSize: '1rem' }}>
                标星股票：eps、gaap eps两值相差>=80%}
              </div>
              <div style={{ margin: 5, fontSize: '1rem' }}>
                共计：{currentDataSource.length}&nbsp;&nbsp;&nbsp;跑分时间：
                {stocks.list.length === 0 ? null : stocks.list[0].uploadTime}
              </div>
              <StandardTable
                selectedRows={selectedRows}
                loading={listLoading}
                data={stocks}
                columns={columnsBeta}
                style={{ tableLayout: 'fixed' }}
                className={styles.TableLayout}
                scroll={{ x: window.outerWidth < 400 ? 900 : 1400, y: 618 }}
                bordered
                onChange={this.handleStandardTableChange}
                pagination={false}
                onRow={record => {
                  const res = record;
                  return {
                    onClick: event => {
                      if (this.doubleClick) {
                        this.doubleClick(res);
                      }
                    },
                  };
                }}
                // rowKey="id"
              />
            </div>
          )}
          <Modal
            destroyOnClose
            footer={null}
            visible={modalVisible}
            title={codes}
            width={window.innerWidth * 0.9}
            centered
            onOk={this.cancelHandle.bind(this)}
            onCancel={this.cancelHandle.bind(this)}
          >
            <TimelineChartSeven height={document.body.clientHeight * 0.8} data={chart} />
          </Modal>
        </Card>
      </PageHeaderWrapper>
    );
  }

  componentDidMount() {
    const { dispatch } = this.props;

    /* 导入列表数据 */
    dispatch({
      type: 'runpoints/GetRunPoints',
      payload: 1,
      callback: res => {
        this.setState({
          currentDataSource: res.list,
        });
      },
    });
  }

  componentWillUnmount() {}
}

export default RunPoints;
